﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SomeContracts;
using System.Diagnostics;
using CServiceStack.ServiceHost;
using System.Threading;
using EAPWrapper;
using System.Threading.Tasks;
using Ctrip.SOA.Comm;

namespace SomeServices
{
    //[IncomingHub(Method = "GET", Name = "log")]
    //[OutgoingHub(Method = "GET", Name = "log")]

    public class TingService : ITingService
    {
        private static readonly String respString;
        static TingService()
        {

            int loops = 10 * 1024 * 1024;
            Byte[] buffer = new Byte[loops];

            Random r = new Random(100);
            for (int i = 0; i < loops; i++)
            {
                int v = r.Next(200);
                buffer[i] = Byte.Parse(v + string.Empty);
            }
            respString = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
        }
        //[ThrottlingRequestFilter("SomeServices.TingService.Ring", 10)]
        //[ThrottlingResponseFilter("SomeServices.TingService.Ring")]
        //[ETagResponseFilter]
        [Route("/ring/get/{RingName}", "GET")]
        public RingResponseType Ring(RingRequestType request)
        {

            #region request
            string requestbody = @"<?xml version=""1.0""?>
<request>
<header culture=""cn"" userid=""hotel.wsuser"" requesttype=""hotel.product.isbookableservice.rscwebservicebookchecker"" asyncrequest=""false"" />
<rscwebservicerequestentity xmlns:xsi=""http://www.w3.org/2001/xmlschema-instance"" xmlns:xsd=""http://www.w3.org/2001/xmlschema"">
<hotelordercontententity xsi:type=""rschotelordercontentrequestentity"">
<arrival>2012-03-01t00:00:00</arrival>
<balancetype>pp</balancetype>
<clientcomefrom>1</clientcomefrom>
<clientname>xiaoxiao</clientname>
<corpuserid />
<customertype>f</customertype>
<departure>2012-03-05t00:00:00</departure>
<earlyarrivaltime>2012-03-01t12:00:00</earlyarrivaltime>
<formatremark />
<holddeadline>9999</holddeadline>
<ischangeclientdata>false</ischangeclientdata>
<isconfirmguarantee>false</isconfirmguarantee>
<isinrange />
<isneedusefgtogetlastcancel>false</isneedusefgtogetlastcancel>
<isnewprocanuse>true</isnewprocanuse>
<ispreliminary>false</ispreliminary>
<language>cn</language>
<latearrivaltime>2012-03-01t14:00:00</latearrivaltime>
<maxroomcount>8</maxroomcount>
<maxvalidroom>0</maxvalidroom>
<minstate>1</minstate>
<orderid>0</orderid>
<ori_orderid>0</ori_orderid>
<paymenttype />
<persons>1</persons>
<prepayreservetype />
<pricechangeflag>f</pricechangeflag>
<promoteenddate>0001-01-01t00:00:00</promoteenddate>
<promotestartdate>0001-01-01t00:00:00</promotestartdate>
<promotetype>0</promotetype>
<quantity>1</quantity>
<realroomnumber>0</realroomnumber>
<room>187698</room>
<serverfrom />
<uid>123</uid>
<usefg />
<userlimited>9999</userlimited>
<validroom>0</validroom>
</hotelordercontententity>
<contactentity xsi:type=""rschotelordercontactrequestentity"">
<contractname>xiaoxiao</contractname>
<contracttel>12345678</contracttel>
<confirmtype>tel</confirmtype>
<contractemail />
<mobilephone />
<foreignmobile />
<contractfax />
</contactentity>
<invoiceentity xsi:type=""rschotelorderinvoicerequestentity"">
<askforinvoice>0</askforinvoice>
<postcode />
<revaddr />
<revpername />
</invoiceentity>
<operationtype>newhotelorder</operationtype>
<creditcardentity xsi:type=""rsccreditcardrequestentity"">
<cardinfoid>1000</cardinfoid>
<creditcardtype>1</creditcardtype>
</creditcardentity>
</rscwebservicerequestentity>
</request>";
            requestbody = @"<?xml version=""1.0""?>
<Request>
  <Header Version=""1.0,2.0"" UserID=""Hotel.WSUser"" ReferenceID=""1514123013000013801"" RequestID=""edbbf879-b99a-4425-9739-253076b3486f"" RequestType=""Hotel.Booking.ReservationWS.HotelRatePlanRQ"" ClientIP=""172.16.169.218"" AsyncRequest=""false"" Timeout=""0"" MessagePriority=""3"" Environment=""dev"" AssemblyVersion=""2.8.0.1"" RequestBodySize=""0"" SerializeMode=""Xml"" RouteStep=""1""  />
  <HotelRatePlanRQ Version=""1"" TimeStamp=""2014-12-30T13:36:40.6656958+08:00"" SearchCacheLevel=""Live"">
    <POS ServerFrom=""taocan.ctrip.com"" Requestor=""VacationOnline"" />
    <RatePlans>
      <RatePlan BalanceType=""PP"" Quantity=""2"" GuestPerson=""3"">
        <DateRange End=""2015-02-03"" Start=""2015-01-31"" />
        <RoomCandidate RoomID=""2725188"">
          <RatePlan CheckAvlID=""0"" RatePlanID=""0"" />
        </RoomCandidate>
      </RatePlan>
    </RatePlans>
  </HotelRatePlanRQ>
</Request>";
            #endregion
            
            //var task = TAPWSAgent.requestasync(reqestbody);
            //string result = WSAgent.Request(requestbody);
            //var task1 = TAPWSAgent.RequestStringAsync(requestbody);
            //task1.ContinueWith(t =>
            //{
            //    if (t.Exception != null)
            //    {
            //        t.Exception.Handle(ex =>
            //        {
            //            Debug.WriteLine(ex);
            //            return true;
            //        });
            //    }
            //});
            //string respStr = task1.Result;
            //Thread.Sleep(200);
            //throw new Exception("exception ring");
            return new RingResponseType()
            {

                result =  new RingData() { Name = request.RingName + "2~"+respString , Times=6} 
                //new List<RingData> 
                //{
                //    new RingData() { Name = request.RingName + "2~"+respString }, 
                //    new RingData() { Name = request.RingName + "1~" }, 
                //    new RingData() { Name = request.RingName + "3~" }
                //}
            };
        }

        public CServiceStack.Common.Types.CheckHealthResponseType CheckHealth(CServiceStack.Common.Types.CheckHealthRequestType request)
        {
            return new CServiceStack.Common.Types.CheckHealthResponseType();
        }

        public static void Init()
        {
            Trace.WriteLine("ting service initialzed...");
        }


        public BellResponseType Bell(BellRequestType request)
        {
            return new BellResponseType() { BellSound = "tada", EntriesPerPage = request.EntriesPerPage, PageNumber = request.PageNumber, TotalEntries = 100, TotalPages = 10 };
        }


        CheckHealthResponseType ITingService.CheckHealth(CheckHealthRequestType request)
        {
            throw new NotImplementedException();
        }

    }


    public class IncomingHubAttribute : Attribute, IHasRequestFilter
    {
        public string Name { get; set; }
        public string Method { get; set; }

        //public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        //{

        //}

        public IHasRequestFilter Copy()
        {
            return this;
        }

        public int Priority
        {
            get
            {
                return -1;
            }
        }


        public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(Method)) return;

            //Trace.AutoFlush = true;
            Trace.WriteLine(string.Format("{0}:{1}", Method,
                       new
                       {
                           Time = DateTime.Now.ToString("G"),
                           Data = req.HttpMethod + " ," + req.RawUrl + ", " + req.GetRawBody()
                       }));
        }
    }

    public class OutgoingHubAttribute : Attribute, IHasResponseFilter
    {
        public string Name { get; set; }
        public string Method { get; set; }


        public IHasResponseFilter Copy()
        {
            return this;
        }

        public int Priority
        {
            get
            {
                return -1;
            }
        }


        //public YourReponseType YourService(YourRequestType request)
        //{       
        //    //在此处埋点被调用次数（服务代码第一行）                     
        //    try
        //    {
                
        //        //业务逻辑代码
        //        ...
        //        ...
        //        //在此处埋点被调用成功次数（try block 代码中 return 之前最后一行)
        //    }
        //    catch(Exception ex)
        //    {
        //        //在此处埋点被调用失败次数，需要注意在try block里面没有捕获异常的逻辑，或者有要抛出来，否则此处无法捕获异常
        //    }
        //    finally{
        //        //在此处埋点响应时间
        //    }
            
        //}

        //public void Invoke()
        //{
            
        //    try//注意try block里面仅包含服务调用代码
        //    {
        //        //在此处埋点调用次数（try block 代码第一行）

        //        //此处为服务调用代码
        //        var response = InvokeSomeService(request);
        //        //此处埋点调用成功次数
        //    }
        //    catch(Exception)
        //    {
        //        //在此处埋点调用失败次数
        //        throw;//如果此处只是埋点，不处理异常，那么要直接抛出去
        //    }
        //    finally
        //    {
        //        //在此处埋点服务响应时长
        //    }
            
        //}


        public void ResponseFilter(IHttpRequest req, IHttpResponse res, object responseDto)
        {
            if (string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(Method)) return;
            Trace.AutoFlush = true;
            Trace.WriteLine(string.Format("{0}:{1}", Method, new { Time = DateTime.Now.ToString("G"), Data = responseDto }));
        }
    }
}
